package servlet;

import com.alibaba.fastjson.JSON;
import entity.Oss;
import service.Impl.OssServiceImpl;
import service.OssService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/Oss.action")
public class OssServlet extends HttpServlet {
    OssService ossService = new OssServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = (req.getParameter("opr") == null || "".equals(req.getParameter("opr")))
                ? "list" : req.getParameter("opr");
        switch (opr){
            case "list":
                List<Oss> ossList = ossService.selectAll();
                String json = JSON.toJSONString(ossList);
                resp.getWriter().print(json);
                return;
            case "selectName":
                String bucketName1 = req.getParameter("bucketName");
                Oss oss1 = ossService.selectBucketName(bucketName1);
                String json1 = JSON.toJSONString(oss1);
                resp.getWriter().print(json1);
                return;
            case "add":
                String bucketName = req.getParameter("bucketName");
                String type = req.getParameter("type");
                String permission = req.getParameter("permission");

                Oss oss = new Oss();
                oss.setBucketName(bucketName);
                oss.setType(type);
                oss.setPermission(permission);
                boolean flag = ossService.add(oss);
                Map map = new HashMap();
                if (flag) {
                    map.put("code", "ok");
                } else {
                    map.put("code", "error");
                }
                resp.getWriter().print(JSON.toJSONString(map));
                return;
            case "update":
                String bucketName2 = req.getParameter("id");
                String permission1 = req.getParameter("permission");
                boolean updateOss = ossService.updatePermission(bucketName2,permission1);
                String json2 = JSON.toJSONString(updateOss);
                resp.getWriter().print(json2);

        }
    }
}
